package com.qike.baoxiu.tools;

import com.auth0.jwt.JWT;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Eric.zhou
 * @Date: 2019/9/5 10:23
 */
/*
 * @author MRC
 * @date 2019年4月5日 下午1:14:53
 * @version 1.0
 */
public class TokenUtil {

    public static Integer getTokenUserId() {
        String token = getRequest().getHeader("token");// 从 http 请求头中取出 token
        if (token==null|| StringUtils.isEmpty(token)){
            return null;
        }
        String userId = JWT.decode(token).getAudience().get(0);
        return Integer.valueOf(userId);
//        return 9;
    }

    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }
}
